<?php


namespace backend\modules\actionlogs\controllers;

use Yii;
use yii\web\Controller;
use common\plugins\actionlog\main\PluginBehavior;
use backend\modules\actionlogs\models\ActionLogs;
use backend\modules\actionlogs\models\searchs\ActionLogs as ActionLogsSearch;

/**
 * description of DefaultController
 *
 * @author FireLoong
 */
class DefaultController extends Controller
{
    const EVENT_AFTER_LOG_PURGE = 'afterLogPurge';
    const EVENT_AFTER_LOG_EXPORT = 'afterLogExport';

    /**
     * {@inheritDoc}
     */
    public function behaviors()
    {
        $pluginBehavior = class_exists(PluginBehavior::class) ? [PluginBehavior::class] : [];
        return $pluginBehavior;
    }

    /**
     * 显示会员操作日志及删除导出日志
     * @return string
     * @throws \Throwable
     * @throws yii\db\StaleObjectException
     */
    public function actionIndex()
    {
        $request = Yii::$app->request;
        if ($request->isPost) {
            $session = Yii::$app->session;
            if ($request->post('purge')) {
                ActionLogs::deleteAll();
                $this->trigger(self::EVENT_AFTER_LOG_PURGE);
            } elseif ($request->post('exportSelectedLogs')) {
                $actionLogs = ActionLogs::findAll($request->post('selection'));
                try {
                    $this->exportLogs($actionLogs);
                } catch (\yii\base\InvalidConfigException $e) {
                    $session->addFlash('error', $e->getMessage());
                }
            } elseif ($request->post('exportAllLogs')) {
                $actionLogs = ActionLogs::find()->all();
                try {
                    $this->exportLogs($actionLogs);
                } catch (\yii\base\InvalidConfigException $e) {
                    $session->addFlash('error', $e->getMessage());
                }
            } else {
                $actionLogs = ActionLogs::findAll($request->post('selection'));
                $result = false;
                foreach ($actionLogs as $actionLog) {
                    if ($actionLog->delete()) {
                        $result = true;
                    } else {
                        $session->addFlash('error', implode('<br>', $actionLog->getErrors()));
                    }
                }
                if ($result) {
                    $this->trigger(self::EVENT_AFTER_LOG_PURGE);
                }
            }
        }
        $searchModel = new ActionLogsSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->getQueryParams());
        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider
        ]);
    }

    /**
     * 导出会员操作日志
     * @param array $actionLogs 操作日志数据
     * @throws \yii\base\InvalidConfigException
     */
    private function exportLogs($actionLogs)
    {
        $rows[] = ['Id', 'Message', 'Date', 'Ip'];
        $formatter = Yii::$app->formatter;
        foreach ($actionLogs as $actionLog) {
            $message = json_decode($actionLog->message, true);
            $msg = Yii::t('plg_actionlog', $actionLog->info, $message);
            $rows[] = [
                'id' => $actionLog->id,
                'message' => strip_tags($msg),
                'Date' => $formatter->asDatetime($actionLog->log_date, 'php:Y-m-d H:i:s T'),
                'ip' => $actionLog->ip_address
            ];
        }

        $fileName = 'logs_' . $formatter->asDatetime(time(), 'php:Y_m_d_His_T') . '.csv';
        $csvHeaders = Yii::$app->response->setDownloadHeaders($fileName);

        $out = fopen('php://output', 'w');
        foreach ($rows as $row) {
            fputcsv($out, $row);
        }
        $csv = stream_get_contents($out);
        fclose($out);

        $this->trigger(self::EVENT_AFTER_LOG_EXPORT);

        return $csvHeaders->send();
    }
}
